#!/usr/bin/env bash

set -euxo pipefail
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
ROOT_DIR=$( cd -- "$SCRIPT_DIR/.." &> /dev/null && pwd )
# OHPB_DIR=$( cd -- "$ROOT_DIR/../openharmony_prebuilts" &> /dev/null && pwd )
# NAME="$( basename -- "$ROOT_DIR" )"
NAME=ohos
WS_DIR=/workspace

cd "$SCRIPT_DIR"

IMAGE_DEPS="${IMAGE_DEPS:-ohos_deps}"
IMAGE_OHPB="${IMAGE_DEV:-ohos_ohpb}"

docker build  \
    -t "$IMAGE_DEPS" \
    deps

docker build \
    --build-arg "UID=$( id -u )" \
    --build-arg "GID=$( id -g )" \
    -t "$IMAGE_OHPB" \
    ohpb

PREBUILTS_VOLUME=ohos_prebuilts
(
    cd "$ROOT_DIR"
    mkdir -p .home
    export HOME="$ROOT_DIR"/.home
    build/prebuilts_download.sh --no-check-certificatie --skip-ssl
    chmod a+x prebuilts/tool/command-line-tools/hvigor/bin/hvigorw

    docker volume rm $PREBUILTS_VOLUME
    docker run -v "$PREBUILTS_VOLUME":/data --name helper busybox true
    docker cp "$ROOT_DIR/prebuilts/." helper:/data || docker rm helper
    docker rm helper
)

exit

docker run --rm -it \
    --mount "type=bind,src=$ROOT_DIR,dst=$WS_DIR/$NAME" \
    --mount "type=volume,src=$PREBUILTS_VOLUME,dst=$WS_DIR/$NAME/prebuilts" \
    -w "$WS_DIR/$NAME" \
    "$IMAGE_OHPB"


exit

NODE_VERSION="14.21.1"
HOST_DIR=linux-x86
PYTHON3_DIR=$(realpath "$ROOT_DIR"/prebuilts/python/"$HOST_DIR"/*/ | tail -1)

ADD_PATH=()
ADD_PATH+=(
    "$ROOT_DIR/prebuilts/build-tools/$HOST_DIR/bin"
    "$PYTHON3_DIR/bin"
    "$ROOT_DIR/prebuilts/build-tools/common/nodejs/node-v${NODE_VERSION}-${HOST_DIR}/bin"
    "$ROOT_DIR/prebuilts/build-tools/common/oh-command-line-tools/ohpm/bin"
    "$ROOT_DIR}/prebuilts/tool/command-line-tools/bin"
)

NODE_HOME=${SOURCE_ROOT_DIR}/prebuilts/build-tools/common/nodejs/node-v${NODE_VERSION}-${HOST_DIR}


docker build \
    --build-arg "ADD_PATH=$( IFS=: ; echo "${ADD_PATH[*]}" )" \
    --build_arg "NODE_HOME=$NODE_HOME"
